#include "terminalwidget.h"
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QScrollBar>
#include <QApplication>
#include <QClipboard>
#include <QFontDatabase>
#include <QTextDocument>
#include <QTextBlock>
#include <QTextLayout>
#include <QTextCursor>
#include <QKeyEvent>
#include <QMouseEvent>
#include <QWheelEvent>
#include <QFocusEvent>
#include <QEvent>
#include <QDebug>
#include <QRegularExpression>
#include <QTimer>

// ANSI颜色定义
const QColor TerminalWidget::ansiColors[16] = {
    QColor(0, 0, 0),         // 黑色
    QColor(255, 0, 0),       // 红色
    QColor(0, 255, 0),       // 绿色
    QColor(255, 255, 0),     // 黄色
    QColor(0, 0, 255),       // 蓝色
    QColor(255, 0, 255),     // 洋红
    QColor(0, 255, 255),     // 青色
    QColor(255, 255, 255),   // 白色
    QColor(128, 128, 128),   // 暗灰色
    QColor(255, 128, 128),   // 亮红色
    QColor(128, 255, 128),   // 亮绿色
    QColor(255, 255, 128),   // 亮黄色
    QColor(128, 128, 255),   // 亮蓝色
    QColor(255, 128, 255),   // 亮洋红
    QColor(128, 255, 255),   // 亮青色
    QColor(255, 255, 255)    // 亮白色
};

const QMap<QString, int> TerminalWidget::colorNames = {
    {"black", 0}, {"red", 1}, {"green", 2}, {"yellow", 3},
    {"blue", 4}, {"magenta", 5}, {"cyan", 6}, {"white", 7},
    {"brightblack", 8}, {"brightred", 9}, {"brightgreen", 10},
    {"brightyellow", 11}, {"brightblue", 12}, {"brightmagenta", 13},
    {"brightcyan", 14}, {"brightwhite", 15}
};

TerminalWidget::TerminalWidget(QWidget *parent)
    : QWidget(parent)
    , m_sshSession(nullptr)
    , m_historyIndex(0)
    , m_cursorPosition(0)
    , m_insertMode(false)
    , m_cursorVisible(true)
    , m_updatePending(false)
{
    // 创建终端显示组件
    m_terminalDisplay = new QPlainTextEdit(this);
    m_terminalDisplay->setReadOnly(false);
    m_terminalDisplay->setLineWrapMode(QPlainTextEdit::NoWrap);
    m_terminalDisplay->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    m_terminalDisplay->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
    m_terminalDisplay->installEventFilter(this);

    // 设置默认字体
    QFont font("Consolas", 10);
    font.setFixedPitch(true);
    m_terminalDisplay->setFont(font);

    // 设置默认颜色
    QPalette palette = m_terminalDisplay->palette();
    palette.setColor(QPalette::Base, Qt::black);
    palette.setColor(QPalette::Text, Qt::white);
    m_terminalDisplay->setPalette(palette);

    // 创建布局
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->setContentsMargins(0, 0, 0, 0);
    layout->addWidget(m_terminalDisplay);

    // 初始化格式
    initializeFormats();
    resetFormat();

    // 创建定时器
    m_cursorTimer = new QTimer(this);
    connect(m_cursorTimer, &QTimer::timeout, this, &TerminalWidget::updateCursor);
    m_cursorTimer->start(500); // 500ms间隔

    m_updateTimer = new QTimer(this);
    m_updateTimer->setSingleShot(true);
    connect(m_updateTimer, &QTimer::timeout, this, [this]() {
        if (m_updatePending) {
            m_updatePending = false;
            // 这里可以添加批量更新逻辑
        }
    });

    // 设置焦点策略
    setFocusPolicy(Qt::StrongFocus);
    setAttribute(Qt::WA_InputMethodEnabled, false);

    // 显示欢迎信息
    appendText("SSH Terminal Ready. Connect to a remote host to begin.\n");
}

TerminalWidget::~TerminalWidget()
{
    clearSession();
}

void TerminalWidget::setSshSession(SshSession *session)
{
    if (m_sshSession == session) {
        return;
    }

    clearSession();

    m_sshSession = session;

    if (m_sshSession) {
        // 连接信号
        connect(m_sshSession, &SshSession::shellOutput, this, &TerminalWidget::onShellOutput);
        connect(m_sshSession, &SshSession::shellError, this, &TerminalWidget::onShellError);
        connect(m_sshSession, &SshSession::stateChanged, this, &TerminalWidget::onSessionStateChanged);

        // 如果会话已经准备好，打开shell
        if (m_sshSession->state() == SshSession::Authenticated) {
            m_sshSession->openShell();
        }
    }
}

void TerminalWidget::clearSession()
{
    if (m_sshSession) {
        // 断开信号连接
        disconnect(m_sshSession, nullptr, this, nullptr);
        m_sshSession = nullptr;
    }

    // 清理状态
    m_currentDirectory.clear();
    m_sessionTitle.clear();
    m_commandBuffer.clear();
    m_cursorPosition = 0;
    m_historyIndex = 0;
}

bool TerminalWidget::hasSession() const
{
    return m_sshSession != nullptr;
}

void TerminalWidget::clear()
{
    m_terminalDisplay->clear();
    resetFormat();
    appendText("Terminal cleared.\n");
}

void TerminalWidget::reset()
{
    clear();
    clearHistory();
    m_currentDirectory.clear();
    m_sessionTitle.clear();
    resetFormat();
}

void TerminalWidget::copy()
{
    QTextCursor cursor = m_terminalDisplay->textCursor();
    if (cursor.hasSelection()) {
        QClipboard *clipboard = QApplication::clipboard();
        clipboard->setText(cursor.selectedText());
    }
}

void TerminalWidget::paste()
{
    QClipboard *clipboard = QApplication::clipboard();
    QString text = clipboard->text();

    if (!text.isEmpty()) {
        if (m_sshSession && m_sshSession->isConnected()) {
            // 发送到远程shell
            m_sshSession->sendShellData(text.toUtf8());
        } else {
            // 插入到命令缓冲区
            m_commandBuffer.insert(m_cursorPosition, text);
            m_cursorPosition += text.length();
            updateDisplay();
        }
    }
}

void TerminalWidget::zoomIn()
{
    QFont font = m_terminalDisplay->font();
    int size = font.pointSize();
    if (size < 72) {
        font.setPointSize(size + 1);
        m_terminalDisplay->setFont(font);
    }
}

void TerminalWidget::zoomOut()
{
    QFont font = m_terminalDisplay->font();
    int size = font.pointSize();
    if (size > 6) {
        font.setPointSize(size - 1);
        m_terminalDisplay->setFont(font);
    }
}

void TerminalWidget::resetZoom()
{
    QFont font("Consolas", 10);
    font.setFixedPitch(true);
    m_terminalDisplay->setFont(font);
}

QStringList TerminalWidget::getHistory() const
{
    return m_commandHistory;
}

void TerminalWidget::setHistory(const QStringList &history)
{
    m_commandHistory = history;
    m_historyIndex = m_commandHistory.size();
}

void TerminalWidget::clearHistory()
{
    m_commandHistory.clear();
    m_historyIndex = 0;
}

void TerminalWidget::setFont(const QFont &font)
{
    m_terminalDisplay->setFont(font);
}

void TerminalWidget::setColors(const QColor &background, const QColor &foreground)
{
    QPalette palette = m_terminalDisplay->palette();
    palette.setColor(QPalette::Base, background);
    palette.setColor(QPalette::Text, foreground);
    m_terminalDisplay->setPalette(palette);

    m_defaultFormat.setForeground(foreground);
    m_defaultFormat.setBackground(background);
}

void TerminalWidget::setCursorColor(const QColor &color)
{
    m_cursorColor = color;
}

void TerminalWidget::setScrollbackLines(int lines)
{
    // 设置最大行数
    m_terminalDisplay->setMaximumBlockCount(lines);
}

void TerminalWidget::sendCommand(const QString &command)
{
    if (m_sshSession && m_sshSession->isConnected()) {
        m_sshSession->sendShellCommand(command);
    } else {
        executeLocalCommand(command);
    }
}

void TerminalWidget::sendText(const QString &text)
{
    if (m_sshSession && m_sshSession->isConnected()) {
        m_sshSession->sendShellData(text.toUtf8());
    } else {
        m_commandBuffer += text;
        m_cursorPosition += text.length();
        updateDisplay();
    }
}

void TerminalWidget::sendKey(int key, Qt::KeyboardModifiers modifiers)
{
    QKeyEvent event(QEvent::KeyPress, key, modifiers);
    keyPressEvent(&event);
}

void TerminalWidget::keyPressEvent(QKeyEvent *event)
{
    if (!m_terminalDisplay->hasFocus()) {
        m_terminalDisplay->setFocus();
    }

    // 如果连接到远程会话，直接发送按键
    if (m_sshSession && m_sshSession->isConnected()) {
        handleRemoteKeyPress(event);
        return;
    }

    // 本地命令处理
    handleLocalKeyPress(event);
}

void TerminalWidget::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::MiddleButton) {
        // 中键粘贴
        paste();
        event->accept();
        return;
    }

   QWidget::mousePressEvent(event);
}

void TerminalWidget::mouseDoubleClickEvent(QMouseEvent *event)
{
    // 双击选择单词
    QTextCursor cursor = m_terminalDisplay->cursorForPosition(event->pos());
    cursor.select(QTextCursor::WordUnderCursor);
    m_terminalDisplay->setTextCursor(cursor);

    QWidget::mouseDoubleClickEvent(event);
}

void TerminalWidget::wheelEvent(QWheelEvent *event)
{
    // 处理鼠标滚轮
    if (event->modifiers() & Qt::ControlModifier) {
        // Ctrl+滚轮缩放
        if (event->angleDelta().y() > 0) {
            zoomIn();
        } else {
            zoomOut();
        }
        event->accept();
        return;
    }

    QWidget::wheelEvent(event);
}

void TerminalWidget::focusInEvent(QFocusEvent *event)
{
    QWidget::focusInEvent(event);
    m_terminalDisplay->setFocus();
    updateCursor();
}

void TerminalWidget::focusOutEvent(QFocusEvent *event)
{
    QWidget::focusOutEvent(event);
    m_cursorVisible = false;
    updateCursor();
}

bool TerminalWidget::eventFilter(QObject *watched, QEvent *event)
{
    if (watched == m_terminalDisplay) {
        switch (event->type()) {
          case QEvent::KeyPress:
            keyPressEvent(static_cast<QKeyEvent*>(event));
            return true;
        default:
            break;
        }
    }

    return QWidget::eventFilter(watched, event);
}

void TerminalWidget::onShellOutput(const QByteArray &data)
{
    QString text = QString::fromUtf8(data);
    qDebug()<<"[Recv]"<<text;
    processAnsiEscape(text.toUtf8());
}

void TerminalWidget::onShellError(const QByteArray &data)
{
    QString text = QString::fromUtf8(data);
    // 错误输出通常使用红色显示
    QTextCharFormat errorFormat = m_currentFormat;
    errorFormat.setForeground(Qt::red);
    appendText(text, errorFormat);
    qDebug()<<"[Error]"<<text<<endl;
}

void TerminalWidget::onSessionStateChanged(SshSession::SessionState state)
{
    switch (state) {
    case SshSession::Disconnected:
        appendText("\nConnection lost.\n");
        break;
    case SshSession::Connected:
        appendText("Connected to server.\n");
        break;
    case SshSession::Authenticated:
        appendText("Authentication successful.\n");
        // 认证成功后打开shell
        if (m_sshSession) {
            m_sshSession->openShell();
        }
        break;
    case SshSession::Ready:
        appendText("Shell ready. You can now enter commands.\n");
        resetFormat();
        break;
    case SshSession::Error:
        appendText("Connection error.\n");
        break;
    default:
        break;
    }
}

void TerminalWidget::onSelectionChanged()
{
    // 选择改变时的处理
    QTextCursor cursor = m_terminalDisplay->textCursor();
    if (cursor.hasSelection()) {
        // 可以在这里添加选择相关的处理
    }
}

void TerminalWidget::updateCursor()
{
    m_cursorVisible = !m_cursorVisible;
    if (m_terminalDisplay->hasFocus()) {
        m_terminalDisplay->setCursorWidth(m_cursorVisible ? 1 : 0);
    }
}

//处理ANSI转义序列，将接收到的数据解析并应用到终端显示上
void TerminalWidget::processAnsiEscape(const QByteArray &data)
{
    QString text = QString::fromUtf8(data);
    int pos = 0;
    int length = text.length();

    while (pos < length)
    {
        if (text[pos] == '\x08') // 处理退格键
        {
            QTextCursor cursor = m_terminalDisplay->textCursor();
            if (!cursor.atStart()) {
                qDebug()<<"[Ok]backspace"<<text[pos]<<endl;
                pos++;
                continue;
            }
        }

        if (text[pos] == '\x1B') // ANSI转义序列
        {
            if (pos + 1 < length && text[pos + 1] == '[') // CSI序列
            {
                int end = pos + 2;
                while (end < length && text[end] >= 0x20 && text[end] <= 0x3F) // 参数部分：0x20到0x3F
                {
                    end++;
                }
                if (end < length && text[end] >= 0x40 && text[end] <= 0x7E) // 命令字符：0x40到0x7E
                {
                    QString sequence = text.mid(pos, end - pos + 1);
                    qDebug()<<"[ANSI]"<<sequence<<endl;;
                    parseAnsiSequence(sequence);
                    pos = end + 1;
                    continue;
                }
            }
            else if (pos + 1 < length && text[pos + 1] == ']') // OSC序列
            {
                int end = pos + 2;
                while (end < length && text[end] != '\x07' && text[end] != '\x1B') {
                    end++;
                }
                if (end < length) {
                    // 跳过OSC序列
                    pos = end + 1;
                    continue;
                }
            }
        }
        else if(text[pos] == '\x07')//忽略终止符
        {
            // 终止符忽略，避免显示乱码
            qDebug()<<"[End]"<<text[pos]<<endl;;
            return;
        }
        else
        {
            // 普通文本
            int start = pos;
            while (pos < length && text[pos] != '\x1B') {
                pos++;
            }

            if (pos > start) {
                QString plainText = text.mid(start, pos - start);
                QTextCursor cursor = m_terminalDisplay->textCursor();
                if(cursor.atEnd())
                {
                    qDebug()<<"[AppTxt]txt Data"<<plainText<<endl;
                    appendText(plainText, m_currentFormat);
                }
                else if(!cursor.atStart() && !cursor.atEnd())
                {
                    qDebug()<<"[InsTxt]txt Data"<<plainText<<endl;
                    insertTextT(plainText, m_currentFormat);
                }
            }
        }
    }
}

void TerminalWidget::parseAnsiSequence(const QString &sequence)
{
    if (sequence.length() < 3) {
        return;
    }

    // 提取参数和命令
    QString params = sequence.mid(2, sequence.length() - 3);
    QChar command = sequence[sequence.length() - 1];

    if (command == 'm') {
        // SGR (Select Graphic Rendition) 序列
        QStringList paramList = params.split(';', Qt::SkipEmptyParts);
        applySgrSequence(paramList);
    } else if (command == 'H' || command == 'f') {
        // 光标定位
        handleCursorMovement(params);
    } else if (command == 'J') {
        // 清屏
        handleScreenClear(params);
    } else if (command == 'K') {
        // 清除行
        if (params.isEmpty() || params == "0") {
            // 清除到行尾
            qDebug()<<"[Cmd-K]"<<command<<endl;
            QTextCursor cursor = m_terminalDisplay->textCursor();
            cursor.movePosition(QTextCursor::End);
            cursor.movePosition(QTextCursor::Left, QTextCursor::KeepAnchor, 1);
            cursor.removeSelectedText();
        }
    } else if (command == 'A') {
        // 光标上移
        int lines = params.isEmpty() ? 1 : params.toInt();
        QTextCursor cursor = m_terminalDisplay->textCursor();
        for (int i = 0; i < lines; i++) {
            cursor.movePosition(QTextCursor::Up);
        }
        m_terminalDisplay->setTextCursor(cursor);
    } else if (command == 'B') {
        // 光标下移
        int lines = params.isEmpty() ? 1 : params.toInt();
        QTextCursor cursor = m_terminalDisplay->textCursor();
        for (int i = 0; i < lines; i++) {
            cursor.movePosition(QTextCursor::Down);
        }
        m_terminalDisplay->setTextCursor(cursor);
    } else if (command == 'C') {
        // 光标右移
        int cols = params.isEmpty() ? 1 : params.toInt();
        QTextCursor cursor = m_terminalDisplay->textCursor();
        for (int i = 0; i < cols; i++) {
            cursor.movePosition(QTextCursor::Right);
        }
        m_terminalDisplay->setTextCursor(cursor);
    } else if (command == 'D') {
        // 光标左移
        int cols = params.isEmpty() ? 1 : params.toInt();
        QTextCursor cursor = m_terminalDisplay->textCursor();
        for (int i = 0; i < cols; i++) {
            cursor.movePosition(QTextCursor::Left);
        }
        m_terminalDisplay->setTextCursor(cursor);
    }
}

void TerminalWidget::applySgrSequence(const QStringList &params)
{
    if (params.isEmpty()) {
        // 重置所有属性
        resetFormat();
        return;
    }

    for (int i = 0; i < params.size(); i++) {
        int code = params[i].toInt();

        switch (code) {
        case 0: // 重置
            resetFormat();
            break;
        case 1: // 粗体
            m_currentFormat.setFontWeight(QFont::Bold);
            break;
        case 2: // 细体
            m_currentFormat.setFontWeight(QFont::Light);
            break;
        case 3: // 斜体
            m_currentFormat.setFontItalic(true);
            break;
        case 4: // 下划线
            m_currentFormat.setFontUnderline(true);
            break;
        case 7: // 反色
            {
                QColor fg = m_currentFormat.foreground().color();
                QColor bg = m_currentFormat.background().color();
                m_currentFormat.setForeground(bg);
                m_currentFormat.setBackground(fg);
            }
            break;
        case 22: // 正常粗细
            m_currentFormat.setFontWeight(QFont::Normal);
            break;
        case 23: // 非斜体
            m_currentFormat.setFontItalic(false);
            break;
        case 24: // 非下划线
            m_currentFormat.setFontUnderline(false);
            break;
        case 27: // 非反色
            m_currentFormat.setForeground(m_defaultFormat.foreground());
            m_currentFormat.setBackground(m_defaultFormat.background());
            break;
        // 前景色 (30-37)
        case 30: case 31: case 32: case 33: case 34: case 35: case 36: case 37:
            m_currentFormat.setForeground(ansiColors[code - 30]);
            break;
        // 前景色 (90-97) - 亮色
        case 90: case 91: case 92: case 93: case 94: case 95: case 96: case 97:
            m_currentFormat.setForeground(ansiColors[code - 90 + 8]);
            break;
        // 背景色 (40-47)
        case 40: case 41: case 42: case 43: case 44: case 45: case 46: case 47:
            m_currentFormat.setBackground(ansiColors[code - 40]);
            break;
        // 背景色 (100-107) - 亮色
        case 100: case 101: case 102: case 103: case 104: case 105: case 106: case 107:
            m_currentFormat.setBackground(ansiColors[code - 100 + 8]);
            break;
        // 默认前景色
        case 39:
            m_currentFormat.setForeground(m_defaultFormat.foreground());
            break;
        // 默认背景色
        case 49:
            m_currentFormat.setBackground(m_defaultFormat.background());
            break;
        }
    }

    m_terminalDisplay->setCurrentCharFormat(m_currentFormat);
}

void TerminalWidget::handleCursorMovement(const QString &params)
{
    QStringList coords = params.split(';', Qt::SkipEmptyParts);
    int row = coords.size() > 0 ? coords[0].toInt() : 1;
    int col = coords.size() > 1 ? coords[1].toInt() : 1;

    moveCursor(row - 1, col - 1); // 转换为0基索引
}

void TerminalWidget::handleScreenClear(const QString &params)
{
    int mode = params.isEmpty() ? 0 : params.toInt();

    switch (mode) {
    case 0: // 清除到屏幕末尾
        m_terminalDisplay->clear();
        break;
    case 1: // 清除到屏幕开头
        // 简化处理：清空屏幕
        m_terminalDisplay->clear();
        break;
    case 2: // 清除整个屏幕
        m_terminalDisplay->clear();
        break;
    }
}

void TerminalWidget::appendText(const QString &text, const QTextCharFormat &format)
{
    QTextCursor cursor = m_terminalDisplay->textCursor();
    cursor.movePosition(QTextCursor::End);

    // 保存当前位置以便后续滚动
    bool wasAtBottom = m_terminalDisplay->verticalScrollBar()->value() == m_terminalDisplay->verticalScrollBar()->maximum();

    // 应用格式并插入文本
    if (format.isValid()) {
        cursor.setCharFormat(format);
    }
    cursor.insertText(text);

    // 如果原来在底部，滚动到底部
    if (wasAtBottom) {
        scrollToBottom();
    }
}

void TerminalWidget::insertTextT(const QString &text, const QTextCharFormat &format) {
    QTextCursor cursor = m_terminalDisplay->textCursor();
    if (format.isValid()) cursor.setCharFormat(format);

    for (int i = 0; i < text.length(); ++i) {
        if (text[i] != '\b') {
            cursor.insertText(text[i]); // 插入普通字符
        }
    }
    m_terminalDisplay->setTextCursor(cursor); // 更新光标
}



void TerminalWidget::moveCursor(int row, int col)
{
    QTextCursor cursor = m_terminalDisplay->textCursor();
    cursor.movePosition(QTextCursor::Start);

    // 移动到指定行
    for (int i = 0; i < row && cursor.movePosition(QTextCursor::Down); i++) {
        // 移动到下一行
    }

    // 移动到指定列
    for (int i = 0; i < col && cursor.movePosition(QTextCursor::Right); i++) {
        // 移动到右一列
    }

    m_terminalDisplay->setTextCursor(cursor);
}

void TerminalWidget::saveCursor()
{
    // 保存当前光标位置和格式
    // 这里可以实现光标保存功能
}

void TerminalWidget::restoreCursor()
{
    // 恢复光标位置和格式
    // 这里可以实现光标恢复功能
}

void TerminalWidget::processCommand(const QString &command)
{
    if (command.isEmpty()) {
        return;
    }

    // 添加到历史记录
    addToHistory(command);

    // 检查是否是本地命令
    if (command.startsWith("exit") || command.startsWith("quit")) {
        closeSession();
        return;
    } else if (command.startsWith("clear")) {
        clear();
        return;
    } else if (command.startsWith("help")) {
        appendText("Available local commands:\n");
        appendText("  clear    - Clear the terminal\n");
        appendText("  exit     - Exit the session\n");
        appendText("  help     - Show this help\n");
        appendText("  history  - Show command history\n");
        return;
    } else if (command.startsWith("history")) {
        appendText("Command history:\n");
        for (int i = 0; i < m_commandHistory.size(); i++) {
            appendText(QString("  %1: %2\n").arg(i + 1).arg(m_commandHistory[i]));
        }
        return;
    }

    // 执行命令
    if (m_sshSession && m_sshSession->isConnected()) {
        executeRemoteCommand(command);
    } else {
        executeLocalCommand(command);
    }
}

void TerminalWidget::executeLocalCommand(const QString &command)
{
    appendText(QString("%1\n").arg(command));
    appendText("Not connected to a remote host.\n");
    emit commandExecuted(command);
}

void TerminalWidget::executeRemoteCommand(const QString &command)
{
    if (m_sshSession && m_sshSession->isConnected()) {
        m_sshSession->sendShellCommand(command);
        emit commandExecuted(command);
    }
}

void TerminalWidget::addToHistory(const QString &command)
{
    if (!command.trimmed().isEmpty()) {
        m_commandHistory.append(command);
        // 限制历史记录大小
        if (m_commandHistory.size() > 1000) {
            m_commandHistory.removeFirst();
        }
        m_historyIndex = m_commandHistory.size();
    }
}

void TerminalWidget::initializeFormats()
{
    // 初始化默认格式
    m_defaultFormat.setForeground(Qt::white);
    m_defaultFormat.setBackground(Qt::black);
    m_defaultFormat.setFontWeight(QFont::Normal);
    m_defaultFormat.setFontItalic(false);
    m_defaultFormat.setFontUnderline(false);

    resetFormat();

    // 初始化颜色表
    m_textFormats.clear();
    for (int i = 0; i < 16; i++) {
        QTextCharFormat format;
        format.setForeground(ansiColors[i]);
        m_textFormats[QString("fg%1").arg(i)] = format;
    }
}

void TerminalWidget::resetFormat()
{
    m_currentFormat = m_defaultFormat;
    m_terminalDisplay->setCurrentCharFormat(m_currentFormat);
}

QTextCharFormat TerminalWidget::createFormat(int foreground, int background, bool bold, bool italic, bool underline)
{
    QTextCharFormat format = m_defaultFormat;

    if (foreground >= 0 && foreground < 16) {
        format.setForeground(ansiColors[foreground]);
    }
    if (background >= 0 && background < 16) {
        format.setBackground(ansiColors[background]);
    }

    if (bold) {
        format.setFontWeight(QFont::Bold);
    }
    if (italic) {
        format.setFontItalic(true);
    }
    if (underline) {
        format.setFontUnderline(true);
    }

    return format;
}

QString TerminalWidget::getCurrentLine() const
{
    QTextCursor cursor = m_terminalDisplay->textCursor();
    cursor.select(QTextCursor::LineUnderCursor);
    return cursor.selectedText();
}

void TerminalWidget::updateDisplay()
{
    // 更新显示（用于本地命令行编辑）
    if (!m_sshSession || !m_sshSession->isConnected()) {
        // 本地模式下的显示更新
        QTextCursor cursor = m_terminalDisplay->textCursor();
        cursor.movePosition(QTextCursor::End);

        // 查找当前行中的提示符
        QString currentLine = getCurrentLine();
        if (currentLine.startsWith("$ ") || currentLine.startsWith("> ")) {
            // 移动到提示符后
            cursor.movePosition(QTextCursor::StartOfLine);
            cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, 2);
            cursor.movePosition(QTextCursor::EndOfLine, QTextCursor::KeepAnchor);
            cursor.removeSelectedText();
            cursor.insertText(m_commandBuffer);
        } else {
            // 没有提示符，直接添加
            cursor.insertText(m_commandBuffer);
        }

        // 设置光标位置
        cursor.movePosition(QTextCursor::StartOfLine);
        cursor.movePosition(QTextCursor::Right, QTextCursor::MoveAnchor, 2 + m_cursorPosition);
        m_terminalDisplay->setTextCursor(cursor);
    }
}

void TerminalWidget::scrollToBottom()
{
    QScrollBar *scrollBar = m_terminalDisplay->verticalScrollBar();
    scrollBar->setValue(scrollBar->maximum());
}

bool TerminalWidget::isCursorAtEnd() const
{
    QTextCursor cursor = m_terminalDisplay->textCursor();
    return cursor.atBlockEnd();
}

int TerminalWidget::getScrollbackLines() const
{
    return m_terminalDisplay->maximumBlockCount();
}

void TerminalWidget::handleRemoteKeyPress(QKeyEvent *event)
{
    qDebug() << "handleRemoteKeyPress called, key:" << event->key() << "text:" << event->text();
    qDebug() << "SSH session exists:" << (m_sshSession != nullptr) << "connected:" << (m_sshSession ? m_sshSession->isConnected() : false);
    if (event->key() == Qt::Key_Left || event->key() == Qt::Key_Right) {
          event->ignore(); // 忽略左右键事件
          return;
      }
    if (!m_sshSession || !m_sshSession->isConnected()) {
        qDebug() << "handleRemoteKeyPress rejected - no session or not connected";
        return;
    }

    // 处理Ctrl组合键
    if (event->modifiers() & Qt::ControlModifier) {
        switch (event->key()) {
        case Qt::Key_C:
            if (m_terminalDisplay->textCursor().hasSelection()) {
                copy();
            } else {
                m_sshSession->sendShellData("\x03"); // Ctrl+C
            }
            return;
        case Qt::Key_V:
            paste();
            return;
        case Qt::Key_L:
            clear();
            return;
        case Qt::Key_Z:
            m_sshSession->sendShellData("\x1A"); // Ctrl+Z
            return;
        case Qt::Key_D:
            m_sshSession->sendShellData("\x04"); // Ctrl+D
            return;
        }
    }

    // 处理其他按键
    QString text = event->text();
    if (!text.isEmpty()) {
        qDebug()<<"[Ok]key text"<<text;
        m_sshSession->sendShellData(text.toUtf8());
    } else {
        // 处理特殊按键
        QString cmdStr = "";
        switch (event->key()) {
        case Qt::Key_Return:
        case Qt::Key_Enter:
            cmdStr = "\n";
            break;
        case Qt::Key_Backspace:
            cmdStr = "\x08";
            break;
        case Qt::Key_Tab:
            cmdStr = "\t";
            break;
        case Qt::Key_Escape:
            cmdStr = "\x1B";
            break;
        case Qt::Key_Up:
            cmdStr = "\x1B[A";
            break;
        case Qt::Key_Down:
            cmdStr = "\x1B[B";
            break;
        case Qt::Key_Right:
            cmdStr = "\x1B[C";
            break;
        case Qt::Key_Left:
            cmdStr = "\x1B[D";
            break;
        case Qt::Key_Home:
            cmdStr = "\x1B[H";
            break;
        case Qt::Key_End:
            cmdStr = "\x1B[F";
            break;
        case Qt::Key_PageUp:
            cmdStr = "\x1B[5~";
            break;
        case Qt::Key_PageDown:
            cmdStr = "\x1B[6~";
            break;
        case Qt::Key_Insert:
            cmdStr = "\x1B[2~";
            break;
        case Qt::Key_Delete:
            cmdStr = "\x1B[3~";
            break;
        }
        if(!cmdStr.isEmpty())
        {
            qDebug()<<"[SEND]"<<cmdStr<<",utf-8:"<<cmdStr.toUtf8();
            m_sshSession->sendShellData( cmdStr.toUtf8());
        }

    }
}

void TerminalWidget::handleLocalKeyPress(QKeyEvent *event)
{
    // 本地模式下的按键处理
    switch (event->key()) {
    case Qt::Key_Return:
    case Qt::Key_Enter:
        if (!m_commandBuffer.isEmpty()) {
            appendText(QString("$ %1\n").arg(m_commandBuffer));
            processCommand(m_commandBuffer.trimmed());
            m_commandBuffer.clear();
            m_cursorPosition = 0;
            appendText("$ ");
        }
        break;

    case Qt::Key_Backspace:
        if (m_cursorPosition > 0) {
            m_commandBuffer.remove(m_cursorPosition - 1, 1);
            m_cursorPosition--;
            updateDisplay();
        }
        break;

    case Qt::Key_Left:
        if (m_cursorPosition > 0) {
            m_cursorPosition--;
            updateDisplay();
        }
        break;

    case Qt::Key_Right:
        if (m_cursorPosition < m_commandBuffer.length()) {
            m_cursorPosition++;
            updateDisplay();
        }
        break;

    case Qt::Key_Up:
        if (m_historyIndex > 0) {
            m_historyIndex--;
            m_commandBuffer = m_commandHistory.at(m_historyIndex);
            m_cursorPosition = m_commandBuffer.length();
            updateDisplay();
        }
        break;

    case Qt::Key_Down:
        if (m_historyIndex < m_commandHistory.size() - 1) {
            m_historyIndex++;
            m_commandBuffer = m_commandHistory.at(m_historyIndex);
            m_cursorPosition = m_commandBuffer.length();
            updateDisplay();
        } else {
            m_historyIndex = m_commandHistory.size();
            m_commandBuffer.clear();
            m_cursorPosition = 0;
            updateDisplay();
        }
        break;

    case Qt::Key_Home:
        m_cursorPosition = 0;
        updateDisplay();
        break;

    case Qt::Key_End:
        m_cursorPosition = m_commandBuffer.length();
        updateDisplay();
        break;

    case Qt::Key_Tab:
        // Tab补全（简化处理）
        m_commandBuffer += "    ";
        m_cursorPosition += 4;
        updateDisplay();
        break;

    default:
        // 处理其他按键
        if (!event->text().isEmpty()) {
            if (m_insertMode || m_cursorPosition == m_commandBuffer.length()) {
                m_commandBuffer.insert(m_cursorPosition, event->text());
            } else {
                m_commandBuffer.replace(m_cursorPosition, 1, event->text());
            }
            m_cursorPosition += event->text().length();
            updateDisplay();
        }
        break;
    }
}

void TerminalWidget::closeSession()
{
    if (m_sshSession) {
        m_sshSession->disconnect();
        clearSession();
        appendText("Session closed.\n$ ");
    }
}
